package cn.tedu.v3;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * Version 3.0  升级  双向连接【客户端与服务器端相互说话】
 *
 * 优化空间：代码结构、流没有关闭
 */
public class Server {
    private ServerSocket serverSocket;
    private Map<String,String> userDataBase;

    public Server() {
        try {
            serverSocket = new ServerSocket(2222);
            userDataBase=new HashMap<>();
            userDataBase.put("欣欣","123456");
            userDataBase.put("雨雨","654321");
        } catch (BindException e) {
            System.out.println("端口号重复申请，建议换个端口号");
        } catch (IOException e) {
            System.out.println("申请端口号失败....");
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("-----等待客户端连接-----");
                Socket socket = serverSocket.accept();
                String ip = socket.getInetAddress().getHostAddress();
                System.out.println(ip + "客户端连接成功了");
                new Thread(new ClientHandler(socket)).start();
            }
        } catch (IOException e) {
            System.out.println("服务器端通讯断开了");
        } finally {
            if (serverSocket != null && !serverSocket.isClosed()) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("服务器关闭失败");
                }
            }
        }
    }

    public static void main(String[] args) {
        new Server().start();
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String ip;
        private String username;
        private String password;

        public ClientHandler(Socket s) {
            this.socket = s;
            ip = socket.getInetAddress().getHostAddress();
        }

        private boolean Logic(String user,String pass){
            return userDataBase.containsKey(user)&&userDataBase.get(user).equals(pass);
        }
        public void run() {
            PrintWriter pw = null;
            //BufferedReader br=null;
            try {
                //1.读入的定义
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
                //2.定义写出
                pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);
                pw.println("请输入用户名：");
                username = br.readLine();
                pw.println("请输入密码：");
                password = br.readLine();
                if (Logic(username,password)){
                    pw.println("登录成功，欢迎进入聊天室~");
                }else {
                    pw.println("登录失败，用户名或者密码错误！");
                    socket.close();
                }

                //1.1读入功能：存线程中
                new Thread(() -> {
                    try {
                        String message;
                        while ((message = br.readLine()) != null) {
                            System.out.println(ip + "客户端说：" + message);
                            //增加写出一句话：读完卡住等待输入
                            System.out.println("服务器端请输入：");
                        }
                    } catch (IOException e) {
                        System.out.println("客户端读入失败!");
                    }
                }).start();

                //2.1提供写方法：控制台输入
                Scanner input = new Scanner(System.in);//控制台卡住
                while (true) {
                    System.out.println("服务器请输入：");
                    String say = input.nextLine();//得到控制台输入值
                    //打印：服务器端说的文本--打印客户端
                    pw.println(say);
                }
            } catch (NullPointerException e) {
                System.out.println("IO流传入对象，有对象为null！立马核对，建议：查看try块中对象可能赋值为null");
            } catch (UnsupportedEncodingException e) {
                System.out.println("客户端或者服务器端：字符集不一致");
            } catch (IOException e) {
                System.out.println("通讯过程中，传输出现错误");
            } finally {
                /*if (br != null)
                    try {
                        br.close();
                    } catch (Exception e) {
                        System.out.println("结束通讯，关闭失败");
                    }*/
                if (socket != null && !socket.isClosed())
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println("通讯关闭失败~");
                    }
            }
        }
    }
}



